package Export;

import java.awt.Graphics2D;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.swing.JFileChooser;
import javax.swing.JPanel;

import Viewer.DrawPanel;
import Viewer.FileChooserX;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * This class implements the PDF export of the {@link DrawPanel}.<br>
 * also see:<br>
 * <a href="http://itextpdf.com/itext.php">http://itextpdf.com/itext.php</a>
 * 
 * @author Stefan Lorenz<br>
 * <br>26.11.2012
 */
public class ExportImage {
    
    /**
     * Panel to export as PDF
     */
    private JPanel panel;
    
    /**
     * Filechooser
     */
    private FileChooserX filechooser;

    /**
     * Constructor of the PDF exporter
     * @param panel Panel to export
     * @param filechooser Filechooser
     */
    public ExportImage(JPanel panel, FileChooserX filechooser) {
	this.panel = panel;
	this.filechooser = filechooser;
	export();
    }

    /**
     * Exports the panel
     */
    public void export() {
	try {
	    if (this.filechooser.showSaveDialog(this.panel) == JFileChooser.APPROVE_OPTION) {
		Document document = new Document();
		document.setPageSize(new com.itextpdf.text.Rectangle(this.panel.getWidth(), this.panel.getHeight()));

		String file = this.filechooser.getSelectedFile().getAbsolutePath();
		if (!file.endsWith(".pdf")) {
		    file += ".pdf";
		}

		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
		document.open();
		PdfContentByte contentByte = writer.getDirectContent();
		PdfTemplate template = contentByte.createTemplate(this.panel.getWidth(), this.panel.getHeight());

		Graphics2D g2 = template.createGraphics(this.panel.getWidth(), this.panel.getHeight());
		this.panel.print(g2);
		g2.dispose();
		contentByte.addTemplate(template, 0, 0);
		document.close();
	    }
	} catch (FileNotFoundException e1) {
	    e1.printStackTrace();
	} catch (DocumentException e1) {
	    e1.printStackTrace();
	}
    }
}
